<script setup lang="ts">
import { FormProps } from "@/views/hooks";
import { onMounted, ref } from "vue";
import {
  getPermissionList,
  getRolePermissions,
  Permission
} from "@/api/system";
import { isAllEmpty } from "@pureadmin/utils";

const props = withDefaults(defineProps<FormProps<any>>(), {
  formInline: () => ({
    roleId: "",
    permission: []
  })
});
const newFormInline = ref(props.formInline);
const permissions = ref({});
const loadFlag = ref<boolean>(true);
const loadFlag2 = ref<boolean>(true);

onMounted(() => {
  getRolePermissions(newFormInline.value.roleId).then(res => {
    newFormInline.value.permission = res;
    loadFlag.value = false;
  });
  getPermissionList({ current: 0, size: -1 }).then(res => {
    res.records.forEach(permission => {
      const name = permission?.group ?? "其他";
      if (permissions.value[name]) {
        permissions.value[name] = [...permissions.value[name], permission];
      } else {
        permissions.value[name] = [permission];
      }
    });
    loadFlag2.value = false;
  });
});
</script>

<template>
  <el-scrollbar v-loading="loadFlag && loadFlag2" max-height="400px">
    <el-empty v-if="isAllEmpty(permissions)" />
    <div v-for="(items, group) in permissions" :key="group">
      <el-divider content-position="left">{{ group }}</el-divider>
      <el-checkbox-group v-model="newFormInline.permission">
        <el-checkbox
          v-for="item in items as Array<Permission>"
          :key="item.id"
          :value="item.id"
        >
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
    </div>
  </el-scrollbar>
</template>

<style scoped lang="scss">
:deep(.el-divider__text) {
  color: dimgray;
}
</style>
